<template>
    <div class="w-full">
        <!-- 打开新文件夹 -->
        <div class="mt-[100px] flex justify-center">
            <el-button type="primary" @click="openFolder" icon="plus">打开文件夹</el-button>
        </div>
        <!-- 历史工作空间列表 -->
        <div class="w-[500px] mx-auto mt-[50px]">
            <div class="search-bar">
                <el-input
                    placeholder="请输入内容"
                    v-model="searchText"
                    clearable
                    @input="handleSearchChange"
                ></el-input>
            </div>
            <div class="list mt-8">
                <el-scrollbar height="300px">
                    <div
                        v-for="item in showHistoryList"
                        class="cursor-pointer hover:bg-slate-100 mb-2 p-1 rounded break-all"
                        @click="clickHistory(item.path)"
                    >
                        {{ item.path }}
                    </div>
                    <div v-if="showHistoryList.length === 0" class="text-center text-slate-500">暂无数据</div>
                </el-scrollbar>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { IWorkSpaceHistoryItem } from '@/appUtils/appData/interfaces'
import { selectFolder } from '@/appUtils/dialog'
import { useWorkSpaceStore } from '@/stores/workSpace'
import { useWorkSpaceHistoryStore } from '@/stores/workSpaceHistory'
import { storeToRefs } from 'pinia'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'

// 数据仓库
const workSpaceHistoryStore = useWorkSpaceHistoryStore()
const workSpaceStore = useWorkSpaceStore()
const { list } = storeToRefs(workSpaceHistoryStore)

// 要显示的历史记录
const showHistoryList = ref<IWorkSpaceHistoryItem[]>(list.value || [])

// store变化的时候
watch(list, (newVal) => {
    showHistoryList.value = newVal
})

// 路由
const router = useRouter()

// 搜索内容
const searchText = ref('')

// 打开文件夹
const openFolder = async () => {
    const dirRes = await selectFolder()
    if (dirRes.canceled) return
    const dir = dirRes.filePaths[0]
    await workSpaceStore.open(dir)
    router.push('/workSpace')
}

// 输入的值发生变化
const handleSearchChange = (value: string) => {
    showHistoryList.value = workSpaceHistoryStore.list.filter((item) => item.path.includes(value))
}

// 点击历史记录
const clickHistory = async (dir: string) => {
    await workSpaceStore.open(dir)
    router.push('/workSpace')
}
</script>

<style scoped></style>
